<template>
  <el-card>
    <!-- 单张图片上传 -->
    <div style="text-align: center; width: 200px;">
      <div 
        v-if="!singleImage"
        @click="openDialog"
        style="cursor: pointer; border: 1px dashed #dcdfe6; border-radius: 4px; height: 120px; display: flex; align-items: center; justify-content: center; margin-bottom: 10px;"
      >
        <div style="text-align: center; color: #909399;">
          <el-icon style="font-size: 28px; margin-bottom: 8px;"><Plus /></el-icon>
          <div>点击上传图片</div>
        </div>
      </div>
      
      <!-- 单图预览 -->
      <div v-if="singleImage" style="position: relative; height: 120px; margin-bottom: 10px; border-radius: 4px; overflow: hidden;">
        <img :src="singleImage" style="width: 100%; height: 100%; object-fit: cover;">
        <div class="image-actions">
          <el-button type="danger" circle size="small" style="position: absolute; top: 5px; right: 5px;" @click.stop="clearImage">
            <el-icon><Delete /></el-icon>
          </el-button>
          <el-button type="primary" circle size="small" @click.stop="previewImage">
            <el-icon><View /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 素材选择对话框 -->
    <el-dialog v-model="dialogVisible" title="选择图片" width="1000px" destroy-on-close>
      <manage :flag="1" @selectImage="selectMedia" />
    </el-dialog>
    
    <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="[singleImage]"
      :initial-index="0"
      @close="previewVisible = false"
    />
  </el-card>
</template>

<script setup>
import { ref, watch } from 'vue'
import { Plus, Delete, View } from '@element-plus/icons-vue'
import manage from "@/views/function/material/Image/index.vue"

// 定义props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

// 定义emit事件
const emit = defineEmits(['upload-success', 'update:modelValue'])

// 状态数据
const dialogVisible = ref(false)
const singleImage = ref(props.modelValue || '')  // 使用props初始化
const previewVisible = ref(false)

// 监听props变化，同步到内部状态
watch(() => props.modelValue, (newValue) => {
  singleImage.value = newValue || ''
}, { immediate: true })

// 打开素材选择对话框
function openDialog() {
  dialogVisible.value = true
}

// 选择媒体后的回调
function selectMedia(url) {
  dialogVisible.value = false
  singleImage.value = url
  // 发送事件给父组件
  emit('upload-success', url)
  emit('update:modelValue', url)
}

// 清除图片
function clearImage() {
  singleImage.value = ''
  emit('upload-success', '')
  emit('update:modelValue', '')
}

// 预览图片
function previewImage() {
  if (singleImage.value) {
    previewVisible.value = true
  }
}
</script>

<style scoped>
/* 图片悬浮显示 */
.image-actions {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.2s;
}

*:hover > .image-actions {
  opacity: 1;
}
</style>